<template>
  <el-dialog
    :title="props.title"
    @close="onClose"
    @opened="onOpended"
    v-model="visible"
    width="800px"
    :close-on-click-modal="false"
  >
    <div class="main">
      <el-scrollbar ref="scrollRef" height="650px" :min-size="10">
        <div class="title">基本设置</div>
        <el-form
          :disabled="props.title.includes('详情')"
          :model="formParams"
          ref="formRef"
          :rules="rules"
          label-width="120px"
        >
          <el-form-item label="城市标签" prop="cityName">
            <el-select
              v-model="formParams.cityName"
              @change="handleChangeCity"
              fit-input-width
              clearable
              placeholder="请选择"
            >
              <el-option
                v-if="type !== 3"
                v-hasPermi="['market:activity:national']"
                label="全国"
                value="全国"
              >
              </el-option>
              <el-option
                v-for="item in cityNameOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="优惠券名称" prop="couponName">
            <el-input
              v-model.trim="formParams.couponName"
              placeholder="请输入优惠券名称，最多16字"
              maxlength="16"
              clearable
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="名称备注" prop="remark">
            <el-input
              v-model.trim="formParams.remark"
              placeholder="仅内部可见，最多30字"
              maxlength="30"
              clearable
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="发放总量" prop="count">
            <el-input-number
              @mousewheel.native.prevent
              :controls="false"
              style="width: 240px"
              v-model="formParams.count"
              :max="100000"
              :min="1"
              :precision="0"
              controls-position="right"
              placeholder="最多100000"
            />张
          </el-form-item>
          <el-form-item label="使用门槛" prop="threshold">
            <el-radio-group v-model="formParams.threshold">
              <el-radio :value="0" :label="0" size="large">无使用门槛</el-radio>
              <br v-if="type !== 5" />
              <el-radio v-if="type !== 5" :value="1" :label="1" size="large">
                订单满
                <el-input-number
                  @mousewheel.native.prevent
                  :controls="false"
                  style="width: 240px"
                  v-model="formParams.symkValue"
                  :max="100000"
                  :min="1"
                  :precision="0"
                  controls-position="right"
                  placeholder="请输入整数"
                />
                元，可用
              </el-radio>
            </el-radio-group>
            <div v-if="type !== 5"> 请输入金额数且使用门槛不能低于优惠内容 </div>
          </el-form-item>
          <el-form-item label="优惠内容" v-if="type === 5">
            <div>免单</div>
          </el-form-item>
          <el-form-item label="优惠内容" required prop="discountMj" v-if="type === 1">
            <div style="width: 100%">
              满减
              <el-input-number
                @mousewheel.native.prevent
                :controls="false"
                style="width: 240px"
                v-model="formParams.discountMj"
                :max="100000"
                :min="0.01"
                :precision="2"
                controls-position="right"
                placeholder="请输入优惠内容"
                @blur="onBlur"
              />
              元
            </div>
            <div> 优惠券面值必须大于等于 0.01 元, 且最大不能超过10 0000元 </div>
          </el-form-item>
          <el-form-item label="优惠内容" required prop="discountZk" v-if="type === 2">
            <div style="width: 100%">
              打
              <el-input-number
                @mousewheel.native.prevent
                :controls="false"
                style="width: 240px"
                v-model="formParams.discountZk"
                :max="9.99"
                :min="0.01"
                :precision="2"
                controls-position="right"
                placeholder="请输入优惠内容"
              />
              折
            </div>
            <div> 优惠券面值必须大于等于 0.01 折, 且最大不能超过9.99折。 </div>
          </el-form-item>
          <el-form-item label="优惠内容" prop="discountsType" v-if="type === 3 || type === 4">
            <el-form
              :disabled="props.title.includes('详情')"
              :model="formParams"
              ref="discountsRef"
              label-width="120px"
              :rules="rules"
            >
              <el-radio-group v-model="formParams.discountsType" @change="changeDiscountsType">
                <el-form-item prop="discountMj">
                  <el-radio :value="1" :label="1"
                    ><div style="width: 100%">
                      满减
                      <el-input-number
                        @mousewheel.native.prevent
                        :controls="false"
                        style="width: 240px"
                        v-model="formParams.discountMj"
                        :max="100000"
                        :min="0.01"
                        :precision="2"
                        controls-position="right"
                        placeholder="请输入优惠内容"
                      />
                      元
                    </div></el-radio
                  >
                  <div> 优惠券面值必须大于等于 0.01 元, 且最大不能超过10 0000元 </div>
                </el-form-item>
                <el-form-item label="" prop="discountZk">
                  <el-radio :value="2" :label="2"
                    ><div style="width: 100%">
                      打
                      <el-input-number
                        @mousewheel.native.prevent
                        :controls="false"
                        style="width: 240px"
                        v-model="formParams.discountZk"
                        :max="9.99"
                        :min="0.01"
                        :precision="2"
                        controls-position="right"
                        placeholder="请输入优惠内容"
                      />
                      折
                    </div></el-radio
                  >
                  <div> 优惠券面值必须大于等于 0.01 折, 且最大不能超过9.99折。 </div>
                </el-form-item>
              </el-radio-group>
            </el-form>
          </el-form-item>
          <!-- <el-form-item label="活动时间" prop="activityInterval">
            <div>
              <el-date-picker
                style="width: 320px"
                v-model="formParams.activityInterval"
                type="datetimerange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                date-format="YYYY-MM-DD"
                time-format="HH:mm"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              />
            </div>
          </el-form-item> -->
          <!-- 用券时间 -->
          <el-form-item label="活动时间" prop="yongquanshijianRadio">
            <el-radio-group v-model="formParams.yongquanshijianRadio">
              <el-radio :value="0" :label="0" size="large">
                <div>
                  <el-date-picker
                    prop="activityTime"
                    style="width: 320px"
                    v-model="formParams.activityTime"
                    type="datetimerange"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    format="YYYY-MM-DD HH:mm"
                    value-format="YYYY-MM-DD HH:mm"
                    date-format="YYYY-MM-DD"
                    time-format="HH:mm"
                    :default-time="[
                      new Date(2000, 1, 1, 0, 0, 0),
                      new Date(2000, 1, 1, 23, 59, 59)
                    ]"
                  />
                </div>
              </el-radio>
              <br />
              <el-radio :value="1" :label="1" size="large">
                <div style="display: flex; align-items: center">
                  领券后立即生效，有效期：
                  <el-input-number
                    @mousewheel.native.prevent
                    :controls="false"
                    style="width: 150px; margin-right: 5px"
                    v-model="formParams.validDays"
                    :max="100000"
                    :min="1"
                    :precision="0"
                    controls-position="right"
                    placeholder="请输入整数"
                  />
                  天
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="Bottom Center prompts info"
                    placement="bottom"
                  >
                    <template #content
                      >有效期按自然天计算，举例:如设置领券后立即<br />生效日有效期2天，用户在5月21日14:00:00时<br />领取优惠券，则该优惠券的可用时间为5月21日<br />的14:00:00至5月22日的23:59:59。</template
                    >
                    <el-icon size="18"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- <el-form-item label="使用时效" prop="useType">
            <el-radio-group v-model="formParams.useType">
              <el-radio :value="1" :label="1" size="large">全天</el-radio>
              <br />
              <el-radio :value="0" :label="0" size="large">
                每天
                <el-time-picker
                  v-model="formParams.activityTimeLimit"
                  is-range
                  range-separator="-"
                  start-placeholder="使用开始时间段"
                  end-placeholder="使用结束时间段"
                />
              </el-radio>
            </el-radio-group>
          </el-form-item> -->
          <div class="title">发放和领取设置</div>
          <el-form-item label="每人限领次数" prop="receiveCount">
            <el-input-number
              @mousewheel.native.prevent
              :controls="false"
              style="width: 240px"
              v-model="formParams.receiveCount"
              :max="200"
              :min="1"
              :precision="0"
              controls-position="right"
              placeholder="请输入整数"
            />
            次
            <div style="width: 100%">最大设置200次</div>
          </el-form-item>
          <div>参与条件</div>

          <el-form-item class="positionBox" label="参与点位" prop="position">
            <el-radio-group
              @change="formParams.positionIdList = []"
              v-model="formParams.position"
              :disabled="!props.title.includes('设置')"
            >
              <div v-show="isNational" class="title2">普通点位</div>
              <el-radio v-show="isNational" :value="0" :label="0"> 全部 </el-radio>
              <el-radio v-show="isNational" :value="1" :label="1">
                指定点位
                <el-select
                  v-show="formParams.position === 1"
                  style="width: 240px"
                  v-model="formParams.positionIdList"
                  multiple
                  filterable
                  clearable
                  fit-input-width
                  collapse-tags
                  collapse-tags-tooltip
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in positionOptions"
                    :key="item.positionId"
                    :label="item.positonName"
                    :value="item.positionId"
                  />
                </el-select>
              </el-radio>
              <span v-show="isNational" style="margin-right: 100px"></span>

              <div v-show="isNational" class="title2">特殊点位</div>

              <el-radio v-show="isNational" :value="2" :label="2"> 全部 </el-radio>
              <el-radio v-show="isNational" :value="3" :label="3">
                指定点位
                <el-select
                  v-show="formParams.position === 3"
                  style="width: 240px"
                  v-model="formParams.positionIdList"
                  multiple
                  filterable
                  clearable
                  fit-input-width
                  collapse-tags
                  collapse-tags-tooltip
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in specialPositionTypeOptions"
                    :key="item.positionId"
                    :label="item.positonName"
                    :value="item.positionId"
                  />
                </el-select>
              </el-radio>
              <el-radio v-show="!isNational" :value="4" :label="4"> 全局参与 </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="参与用户" prop="clientStatus" v-if="type !== 4">
            <el-radio-group v-model="formParams.clientStatus">
              <el-radio :value="1" :label="1" size="large"> 全部用户 </el-radio>
              <br />
              <el-radio v-show="isNational" :value="2" :label="2" size="large">
                新注册用户（未下单的用户）
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="参与用户" prop="clientStatus" v-if="type === 4">
            <el-radio-group v-model="formParams.clientStatus">
              <el-radio :value="2" :label="2" size="large"> 新注册用户（未下单的用户） </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="适用套餐" prop="combo">
            <el-radio-group v-model="formParams.combo">
              <el-radio v-if="type !== 3" :value="0" :label="0" size="large">
                全部套餐可用
              </el-radio>
              <br />
              <el-radio v-show="isNational" :value="1" :label="1" size="large">
                指定套餐可用
                <el-select
                  v-model="formParams.comboIdList"
                  :multiple="type !== 3"
                  filterable
                  clearable
                  collapse-tags
                  collapse-tags-tooltip
                  reserve-keyword
                  placeholder="请搜索套餐名称并且选择"
                  style="width: 240px"
                >
                  <el-option
                    v-for="item in goodsOptions"
                    :key="item.comboId"
                    :label="item.name"
                    :value="item.comboId"
                  />
                </el-select>
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="使用规则" prop="rule">
            <div style="width: 100%">
              <el-input
                v-model="formParams.rule"
                style="width: 300px"
                :autosize="{ minRows: 3, maxRows: 8 }"
                type="textarea"
                maxlength="1000"
                placeholder="请输入内容"
                show-word-limit
              />
            </div>
            <div style="width: 330px">
              <div class="textarea-header">
                <span>示例</span>
                <el-link
                  :underline="false"
                  type="primary"
                  v-copyText="type === 5 ? TEXT_INFO2 : TEXT_INFO"
                  v-copyText:callback="copyTextSuccess"
                  >复制</el-link
                >
              </div>
              <div v-if="type === 5" class="textarea-info"
                >1 ． 霸 王 免 单 优 惠 券 ；<br />
                2 ． 部 分 订 单 商 品 金 额 满 1 2 元 可 用 ；<br />
                3 ． 有 效 期 至 2024—11一24 23：59：59 ；<br />
                4 ． 可 使 用 营 业 点 ： 仅 限 部 分 营 业 点 可 用 ；<br />
                5 ． 优 惠 券 仅 原 价 购 买 时 可 用 。
              </div>
              <div v-else class="textarea-info"
                >1 ． 满 减 优 惠 券 ；<br />
                2 ． 部 分 订 单 商 品 金 额 满 1 2 元 可 用 ；<br />
                3 ． 有 效 期 至 2024—11一24 23：59：59 ；<br />
                4 ． 可 使 用 营 业 点 ： 仅 限 部 分 营 业 点 可 用 ；<br />
                5 ． 优 惠 券 仅 原 价 购 买 时 可 用 。
              </div>
            </div>
          </el-form-item>
          <el-form-item v-show="isNational" label-width="0">
            <el-checkbox
              v-model="formParams.couponCentre"
              label="领券中心（是否允许优惠券公开展示在领券中心）"
              size="large"
              :true-label="1"
              :true-value="1"
              :false-value="0"
              :false-label="0"
              style="margin-right: 20px"
              :checked="formParams.couponCentre === 1"
            />
          </el-form-item>
          <div class="title" style="margin-top: 10px" v-if="formParams.cityName !== '全国'"
            >分享设置</div
          >
          <el-form-item label="分享标题" prop="shareTitle" v-if="formParams.cityName !== '全国'">
            <el-input
              v-model.trim="formParams.shareTitle"
              placeholder="请输入标题名称，最多20字"
              maxlength="20"
              clearable
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="上传图片" prop="shareImg" v-if="formParams.cityName !== '全国'">
            <div
              ><ImageUploadByType
                v-model="formParams.shareImg"
                :isShowTip="false"
                uploadType="1"
                :limit="1"
                :fileSize="10"
              />请上传 大小不超过 10MB 格式为 png/jpg/jpeg 的文件 图片的比例为5:4,
              如500px*400px</div
            >
          </el-form-item>
          <el-form-item v-show="isNational" label-width="0" prop="setting">
            <el-checkbox
              label="活动设置"
              v-model="formParams.setting"
              size="large"
              style="margin-right: 20px"
              @change="handleSetting"
            />
          </el-form-item>
          <div v-if="formParams.setting">
            <el-form-item :required="formParams.setting" label="上传背景" prop="backgroundImg">
              <div
                ><ImageUploadByType
                  v-model="formParams.backgroundImg"
                  :isShowTip="false"
                  uploadType="1"
                  :limit="1"
                  :fileSize="10"
                />请上传 大小不超过10MB，格式为png/jpg/jpeg的文件，图片推荐尺寸750px*2288px</div
              >
            </el-form-item>
            <el-form-item :rules="valueRules" label="按钮文字" prop="buttonName">
              <el-input
                v-model.trim="formParams.buttonName"
                placeholder="请输入按钮文字，最多10字"
                maxlength="10"
                clearable
                style="width: 240px"
              />
            </el-form-item>
            <el-form-item :rules="valueRules" label="活动规则" prop="activityRule">
              <div style="width: 100%">
                <el-input
                  v-model="formParams.activityRule"
                  style="width: 300px"
                  :autosize="{ minRows: 3, maxRows: 8 }"
                  type="textarea"
                  maxlength="1000"
                  placeholder="请输入内容"
                  show-word-limit
                />
              </div>
            </el-form-item>
          </div>
        </el-form>
      </el-scrollbar>
    </div>
    <template #footer v-if="!props.title.includes('详情')">
      <el-button :loading="submit" type="primary" @click="handleAction(true)"> 保存 </el-button>
      <el-button @click="handleAction(false)">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  addActivityApi,
  checkPopupApi,
  getComboListApi,
  getCouponDetailApi,
  getPositionListApi
} from '@/api/marketing/activity'
import { formatTexarea, parseTime } from '@/utils/tools'

import useGlobalStore from '@/store/modules/global'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => globalStore.myCityList)

const TEXT_INFO =
  '1．满减优惠券；\n2．部分订单商品金额满12元可用；\n3．有效期至2024—11一24 23：59：59；\n4．可使用营业点：仅限部分营业点可用；\n5．优惠券仅原价购买时可用。'
const TEXT_INFO2 =
  '1．霸王免单优惠券；\n2．部分订单商品金额满12元可用；\n3．有效期至2024—11一24 23：59：59；\n4．可使用营业点：仅限部分营业点可用；\n5．优惠券仅原价购买时可用。'

const router = useRouter()
const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  flag: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['refresh'])

const scrollRef = ref(null)
const formRef = ref(null)
const discountsRef = ref(null)
const submit = ref(false)

const visible = ref(false)

const formParams = reactive({
  couponName: '',
  remark: '',
  count: null,
  threshold: '',
  discounts: null,
  discountMj: null,
  discountZk: null,
  discountsType: '',
  // huodongTime: '',
  activityTime: '',
  // activityInterval: null,
  activityTimeLimit: null,
  validStartTime: '',
  validEndTime: '',
  receiveCount: null,
  position: '',
  positionIdList: '',
  combo: '',
  comboIdList: '',
  clientStatus: '',
  rule: '',
  popup: 0,
  popupUrl: '',
  couponCentre: 0,
  type: '',
  details: '',
  shareTitle: '',
  shareImg: '',
  backgroundImg: '',
  buttonName: '',
  huodongguize: '',
  setting: false,
  validDays: null,
  yongquanshijianRadio: null,
  // useType: null,
  cityName: ''
})

const goodsOptions = ref([])
const positionOptions = ref([]) // 普通点位
const specialPositionTypeOptions = ref([]) // 特殊点位
const type = ref('')
const isNational = computed(() => {
  if (formParams.cityName !== '全国') {
    formParams.clientStatus = ''
    formParams.combo = ''
    return true
  } else {
    formParams.position = 4
    formParams.clientStatus = 1
    formParams.combo = 0
    return false
  }
})

const checkThreshold = (rule, value, callback) => {
  if (formParams.threshold) {
    if (!formParams.symkValue) {
      callback(new Error('请输入内容'))
    } else if (formParams.symkValue < formParams.discountMj) {
      callback(new Error('使用门槛不能低于满减金额'))
    } else {
      callback()
    }
  } else if (formParams.threshold === 0) {
    callback()
  } else {
    callback(new Error('请选择'))
  }
}
const checkHuodon = (rule, value, callback) => {
  if (formParams.shiyongshixiaoRadio) {
    if (!formParams.shiyongshixiaoTime?.length) {
      callback(new Error(''))
    } else {
      callback()
    }
  } else if (formParams.shiyongshixiaoRadio === 0) {
    callback()
  } else {
    callback(new Error('请选择'))
  }
}
const checkYongquanshijian = (rule, value, callback) => {
  if (formParams.yongquanshijianRadio) {
    if (!formParams.validDays) {
      callback(new Error('请输入有效期'))
    } else {
      callback()
    }
  } else if (formParams.yongquanshijianRadio === 0) {
    if (!formParams.activityTime?.length) {
      callback(new Error('请选择用券时间'))
    } else {
      callback()
    }
  } else {
    callback(new Error('请选择'))
  }
}
const checkPosition = (rule, value, callback) => {
  if (value === 0 || value === 2 || value === 4) {
    callback()
  } else if (value === 1 || value === 3) {
    if (!formParams.positionIdList || !formParams.positionIdList.length) {
      callback(new Error('请选择点位'))
    } else {
      callback()
    }
  } else {
    callback(new Error('请选择'))
  }
}

const checkCombo = (rule, value, callback) => {
  if (value === 1) {
    if (!formParams.comboIdList || !formParams.comboIdList.length) {
      return callback(new Error(''))
    } else {
      callback()
    }
  } else if (value === 0) {
    callback()
  } else {
    callback(new Error('请选择'))
  }
}
const checkImg = (rule, value, callback) => {
  if (formParams.popup) {
    if (!value?.length) {
      console.log(value)
      callback(new Error('请上传弹窗图片'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

const checkDiscountMj = (rule, value, callback) => {
  if (type.value !== 5) {
    if (type.value === 3 || type.value === 4) {
      if (value === null && formParams.discountsType === 1) {
        callback(new Error(''))
      } else {
        callback()
      }
    } else {
      if (value === null) {
        callback(new Error('请输入'))
      } else {
        callback()
      }
    }
  } else {
    callback()
  }
}
const checkDiscountZk = (rule, value, callback) => {
  if (type.value !== 5) {
    if (type.value === 3 || type.value === 4) {
      if (value === null && formParams.discountsType === 2) {
        callback(new Error(''))
      } else {
        callback()
      }
    } else {
      if (value === null) {
        callback(new Error('请输入'))
      } else {
        callback()
      }
    }
  } else {
    callback()
  }
}
const checkBgImg = (rule, value, callback) => {
  if (formParams.setting) {
    if (!value?.length) {
      callback(new Error('请上传背景'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}
const checkActivityTimeLimitRadio = (rule, value, callback) => {
  if (formParams.useType) {
    callback()
  } else if (formParams.useType === 0) {
    if (!formParams.activityTimeLimit?.length) {
      callback(new Error('请选择使用时效'))
    } else {
      callback()
    }
  } else {
    callback(new Error('请选择'))
  }
}
const rules = {
  cityName: [{ required: true, message: '请选择', trigger: 'change' }],
  couponName: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
  count: [{ required: true, message: '请输入发放总量', trigger: ['blur', 'change'] }],
  symkValue: [{ validator: checkThreshold, trigger: 'blur' }],
  threshold: [{ required: true, validator: checkThreshold, trigger: 'change' }],

  discountsType: [{ required: true, message: '请选择', trigger: 'change' }],
  discountMj: [{ validator: checkDiscountMj, trigger: 'blur' }],
  discountZk: [{ validator: checkDiscountZk, trigger: 'blur' }],
  activityTime: [{ required: true, message: '', trigger: 'change' }],
  // activityInterval: [{ required: true, message: '请选择活动时间', trigger: 'change' }],
  activityTimeLimit: [{ required: true, message: '请选择活动时效', trigger: 'change' }],
  receiveCount: [{ required: true, message: '请输入限领次数', trigger: 'blur' }],

  position: [{ required: true, validator: checkPosition, trigger: 'change' }],
  clientStatus: [{ required: true, message: '请选择', trigger: 'change' }],
  combo: [{ required: true, validator: checkCombo, trigger: 'change' }],
  popupUrl: [{ validator: checkImg, trigger: 'change' }],
  rule: [{ required: true, message: '请输入使用规则', trigger: 'blur' }],
  shareTitle: [{ required: true, message: '请输入分享标题', trigger: 'blur' }],
  shareImg: [{ required: true, message: '请上传图片', trigger: 'change' }],
  backgroundImg: [{ validator: checkBgImg, trigger: 'change' }],
  yongquanshijianRadio: [{ required: true, validator: checkYongquanshijian, trigger: 'change' }]
  // useType: [{ required: true, validator: checkActivityTimeLimitRadio, trigger: 'change' }]
}

const valueRules = ref([{ required: false, message: '', trigger: 'blur' }])

function handleSetting() {
  if (formParams.setting) {
    valueRules.value = [{ required: true, message: '请输入', trigger: 'blur' }]
  } else {
    valueRules.value = [{ required: false, message: '', trigger: 'blur' }]
  }
}

function changeDiscountsType() {
  discountsRef.value.validateField('discountMj')
  discountsRef.value.validateField('discountZk')
  formRef.value.validateField('threshold')
}

// 切换城市
function handleChangeCity() {
  getPositions()
  getGoods()
  formParams.positionIdList = []
  formParams.comboIdList = ''
}

function handleCheckboxChange(val) {
  console.log(val, 'val')
  if (val) {
    formParams.popup = 0
    checkPopupApi({ cityName: formParams.cityName }).then((res) => {
      if (res?.data) {
        ElMessageBox.confirm(
          '弹窗已被使用，此活动是否优先使用，使用后替代小程序首页弹窗。',
          '弹窗已被使用',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          }
        )
          .then(() => {
            formParams.popup = 1
          })
          .catch(() => {
            formParams.popup = 0
          })
      } else {
        formParams.popup = 1
      }
    })
  } else {
    console.log(val, 'val')
    formParams.popup = 0
  }
}

function onBlur() {
  if (formParams.threshold !== '') {
    formRef.value.validateField('threshold')
  }
}
function onChange() {
  if (formParams.shiyongshixiaoRadio !== '') {
    formRef.value.validateField('shiyongshijiaoRadio')
  }
}

/** 复制代码成功 */
function copyTextSuccess() {
  ElMessage({
    message: '复制成功',
    type: 'success'
  })
}

function getPositions() {
  getPositionListApi({ cityName: formParams.cityName }).then((res) => {
    positionOptions.value = res?.data?.filter((i) => i?.label === 2)
    specialPositionTypeOptions.value = res?.data?.filter((i) => i?.label === 1)
    console.log('getPositions=================>')
    console.log(specialPositionTypeOptions.value)
    console.log(positionOptions.value)
  })
}
function getGoods() {
  getComboListApi({ cityName: formParams.cityName }).then((res) => {
    goodsOptions.value = res?.data || []
  })
}

function onOpended() {
  formRef.value.clearValidate('combo')
  formRef.value.clearValidate('position')
}

function onClose() {
  formRef.value.resetFields()
  Object.keys(formParams).forEach((key) => {
    formParams[key] = null
  })
  formParams.popup = 0
  formParams.setting = false
  formParams.couponCentre = 0
  scrollRef.value?.setScrollTop(0)
  formParams.discountsType = ''
  visible.value = false
}

function getCouponValue(params) {
  const { threshold, discounts, discountsType, combo, comboIdList } = params
  if (type.value === 5) {
    return '免单'
  } else if (type.value !== 3 || !combo) {
    const firstStr = threshold ? `满${threshold}元，` : `无门槛，`
    const lastStr = discountsType === 1 ? `减${discounts}元` : `打${discounts}折`
    return firstStr + lastStr
  }
  goodsOptions.value.find((i) => {
    return i.comboId === comboIdList[0]
  })
  return (
    goodsOptions.value.find((i) => {
      return i.comboId === comboIdList[0]
    }).name + '兑换'
  )
}

function formatParams() {
  submit.value = true
  // 文本与内容转换成html标签
  const params = { ...formParams }
  params.rule = formatTexarea(formParams.rule)
  params.activityRule = formatTexarea(formParams.activityRule)

  // 图片
  const flag = params.popupUrl?.length && params.popup
  params.popupUrl = flag ? params.popupUrl[0].url : ''
  params.popup = flag ? 1 : 0

  params.shareImg = params.shareImg?.length ? params.shareImg[0].url : ''
  params.setting = params.setting ? 1 : 0
  params.couponCentre = params.couponCentre ? 1 : 0
  if (params.setting) {
    params.backgroundImg = params.backgroundImg?.length ? params.backgroundImg[0].url : ''
  } else {
    params.backgroundImg = ''
    params.buttonName = ''
    params.activityRule = ''
  }
  // 用券时间
  const isActiveTime = !params.yongquanshijianRadio && params.activityTime?.length
  params.validStartTime = isActiveTime ? new Date(params.activityTime[0] + ':00').getTime() : ''
  params.validEndTime = isActiveTime ? new Date(params.activityTime[1] + ':59').getTime() : ''
  // 活动时间
  // params.validStartTime = params.huodongTime?.length ? new Date(params.huodongTime[0] + ':00') : ''
  // params.validEndTime = params.huodongTime?.length ? new Date(params.huodongTime[1] + ':59') : ''
  //使用时效
  // const isShiyongshixiaoTime = !params.yongquanshijianRadio && params.shiyongshixiaoEndTime?.length
  // params.shiyongshixiaoRadio =
  //   params.shiyongshixiaoRadio === 1 ? params.shiyongshixiaoTime : params.shiyongshixiaoRadio
  // params.shiyongshixiaoStartTime = isShiyongshixiaoTime
  //   ? params.shiyongshixiaoEndTime[0] + ':00'
  //   : ''
  // params.shiyongshixiaoEndTime = isShiyongshixiaoTime ? params.shiyongshixiaoEndTime[1] + ':59' : ''

  params.validDays = params.yongquanshijianRadio ? params.validDays : ''
  // 使用门槛
  params.threshold = params.threshold === 1 ? params.symkValue : params.threshold
  // 优惠内容
  if (type.value === 1) {
    params.discounts = params.discountMj
    params.discountsType = 1
  } else if (type.value === 2) {
    params.discounts = params.discountZk
    params.discountsType = 2
  } else if (type.value === 5) {
    params.discounts = null
    params.discountsType = 1
  } else {
    params.discounts = params.discountsType === 1 ? params.discountMj : params.discountZk
  }

  // params.positionIdList =
  //   params.position === 1 ? params.positionIdList : positionOptions.value.map((i) => i.positionId)
  params.comboIdList =
    params.combo === 1 ? params.comboIdList : goodsOptions.value.map((i) => i.comboId)
  if (type.value === 3 && params.combo === 1) {
    params.comboIdList = [params.comboIdList]
  }
  params.details = getCouponValue(params)
  delete params.activityTime
  // delete params.activityInterval
  delete params.symkValue
  delete params.discountMj
  delete params.discountZk
  addActivityApi(params)
    .then(() => {
      visible.value = false
      submit.value = false
      emit('refresh')
      ElMessage({
        message: '活动新建成功',
        type: 'success'
      })
      if (props.flag) {
        router.push('/market/activity')
      }
    })
    .catch(() => {
      submit.value = false
    })
}

function handleAction(confirm) {
  if (confirm) {
    formRef.value?.validate((valid) => {
      if (valid) {
        if (discountsRef.value) {
          discountsRef.value?.validate((e) => {
            if (e) {
              formatParams()
            } else {
              ElMessage({
                message: '提交失败，请校验数据',
                type: 'error'
              })
            }
          })
        } else {
          formatParams()
        }
      } else {
        ElMessage({
          message: '提交失败，请校验数据',
          type: 'error'
        })
        submit.value = false
      }
    })
  } else {
    onClose()
  }
}

function init(val, cityName, couponId) {
  type.value = val
  formParams.type = val
  formParams.cityName = cityName
  getPositions()
  getGoods()
  if (couponId) {
    visible.value = true
    getCouponDetailApi({ couponId }).then((res) => {
      initDeatil(res?.data || {})
    })
  } else {
    formParams.activityTimeLimit = 0
    if (type.value === 4) {
      formParams.clientStatus = 2
    }
    formParams.combo = ''
    if (type.value === 3) {
      formParams.combo = 1
    }
    if (type.value === 5) {
      formParams.threshold = 0
    }
    visible.value = true
  }
}

function initDeatil(detail) {
  console.log('initDeatil', detail)
  Object.keys(formParams).map((i) => {
    formParams[i] = detail[i]
  })
  console.log('initDeatil', formParams)
  formParams.positionIdList = detail.positionIdList
  formParams.comboIdList = detail.combo === 1 ? detail.comboIdList : ''
  if (formParams.type === 3 && formParams.combo === 1) {
    formParams.comboIdList = formParams.comboIdList[0]
  }
  if (detail.validDays) {
    formParams.yongquanshijianRadio = 1
    formParams.activityTime = ''
  } else {
    formParams.yongquanshijianRadio = 0
    formParams.activityTime = [detail.validStartTime, detail.validEndTime]
    formParams.validDays = null
  }
  formParams.symkValue = detail.threshold ? detail.threshold : null
  formParams.threshold = detail.threshold ? 1 : 0
  // formParams.shiyongshixiaoRadio = detail.shiyongshixiaoRadio ? 1 : 0
  // if (detail.shiyongshixiaoRadio) {
  //   formParams.shiyongshixiaoRadio = 1
  //   formParams.shiyongshixiaoTime = ''
  // } else {
  //   formParams.shiyongshixiaoRadio = 0
  //   formParams.shiyongshixiaoTime = [detail.shiyongshixiaoStartTime, detail.shiyongshixiaoEndTime]
  //   formParams.validDays = null
  // }
  // TODO:活动时间和使用时效
  // formParams.huodongTime = [detail.shiyongshixiaoStartTime, detail.shiyongshixiaoEndTime]
  // 优惠内容
  if (formParams.type === 1) {
    formParams.discountMj = detail.discounts
  } else if (formParams.type === 2) {
    formParams.discountZk = detail.discounts
  } else if (formParams.type !== 5) {
    formParams.discountMj = detail.discountsType === 1 ? detail.discounts : null
    formParams.discountZk = detail.discountsType === 2 ? detail.discounts : null
  }
  formParams.popupUrl = detail.popupUrl ? [{ url: detail.popupUrl }] : ''
  formParams.shareImg = detail.shareImg ? [{ url: detail.shareImg }] : ''
  formParams.backgroundImg = detail.backgroundImg ? [{ url: detail.backgroundImg }] : ''
  formParams.rule = formatTexarea(detail.rule, 1)
  formParams.activityRule = formatTexarea(detail.activityRule, 1)
  formParams.setting = formParams.setting ? true : false
}

defineExpose({
  init
})
</script>

<style lang="scss" scoped>
.main {
  position: relative;
  transform: translate3d(0, -20px, 0);
  .title {
    margin-bottom: 20px;
    font-size: 16px;
    font-weight: 600;
  }
  .textarea-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .textarea-info {
    line-height: 18px;
  }
  .upload-wrapper {
    display: flex;
    align-items: start;
  }
  .el-checkbox.el-checkbox--large {
    height: 32px;
  }
}
.el-radio-group .el-radio {
  width: 100%;
}

.positionBox {
  .title2 {
    font-size: 14px;
    font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei',
      Arial, sans-serif;
  }
  .el-radio-group .el-radio {
    width: auto;
  }
  .el-radio-group {
    display: block;
  }
}
</style>
